package jmsTopic;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.jms.JMSException;
import javax.jms.Session;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicSession;
import javax.jms.TopicSubscriber;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.apache.log4j.BasicConfigurator;

public class ConsumerA {
	
	private TopicConnectionFactory conFactory;
	private TopicConnection connection;
	private TopicSession session;
	private TopicSubscriber subscriber;
	private Listener listener;
	
	public ConsumerA(String topicName, String clientId) throws NamingException, JMSException {
		// JNDI cherche ConnectionFactory 
		listener = new Listener();
		InitialContext jndi = new InitialContext();
		try {
//			conFactory = (TopicConnectionFactory) jndi.lookup("java:comp/env/jms/ConnectionFactory");
			conFactory = (TopicConnectionFactory) jndi.lookup("topicConnectionFactory");
		} catch (NamingException e) {
			System.exit(1);
		}
		
		try {
			connection = conFactory.createTopicConnection();
			connection.setClientID(clientId);
			session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
			
			// cherche a JMS TOPIC et creer un Consumer pour recevoir mais il est pas durable
			Topic topic = (Topic) jndi.lookup(topicName);
			
			subscriber = session.createDurableSubscriber(topic, "ConsumerA");		
			subscriber.setMessageListener(listener);
			
			// demarrer la JMS connection 
			connection.start();
			
		} catch (JMSException e) {
			e.printStackTrace();
		} 

	}
	
	public static void main(String[] args) {
		
		BasicConfigurator.configure();
		
		try {
			ConsumerA con = new ConsumerA("MyTopic", "Liying");
			
			BufferedReader commandLine = new BufferedReader(new InputStreamReader(System.in));
			while (true) {
				String s = commandLine.readLine();
				if (s.equalsIgnoreCase("exit")) {
					con.connection.close();
					System.exit(0);
				}
			}
		} catch (NamingException e) {
			e.printStackTrace();
		} catch (JMSException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
